/**
 * Created by rockyren on 15/1/1.
 */
var addressController = angular.module('addressController', ['ui.bootstrap', 'commonServices']);

addressController.controller('addressController', ['$scope', '$modal', 'addressServices', 'errorShowServices',
        function($scope, $modal, addressServices, errorShowServices){
  /**
   * 获取地址列表数据
   */
  function loadAddress() {
    addressServices.get()
      .success(function(data){
        $scope.addressList = data.addressList;

        //找到默认地址
        for(var i=0;i<$scope.addressList.length;i++){
          if($scope.addressList[i].default == true) {
            $scope.$emit('set:address', $scope.addressList[i]);
            break;
          }
        }
      })
      .error(function(data){
        console.log(data.error);
      });
  }
  loadAddress();


  $scope.setAddress = function(curAddress){
    $scope.$emit('set:address', curAddress);
  };

  /**
   * 删除单个列表数据
   * 删除后重新加载地址列表
   * @param id
   */
  $scope.delete = function(id) {
    if(confirm('确定删除地址?') == true){
      addressServices.destroy(id)
        .success(function(data){
          if(data.status && data.status == 'failure') {
            errorShowServices.alertErrorMessage('删除失败:', data.message);
          }else {
            alert('删除成功');
            loadAddress();
          }
        })
        .error(function(data){

        });
    }

  };

  /**
   * 打开新增模态框
   * 传一个空的addressList给控制器(为了与编辑部分相对应)
   * @param size
   * 暂时不测试
   */
  $scope.createAddress = function() {

    //为了便于测试,将modalInstance放到scope作用域中
    $scope.modalInstance = $modal.open({
      templateUrl: 'ngApp/common/tpls/addressModalContent.html',
      controller: 'addressModalController',
      //size: size
      resolve: {
        addressList: null
      }

    });


    //创建单个地址列表数据
    //触发close或dismiss时调用
    $scope.modalInstance.result.then(function(addressData){
        addressServices.store(addressData)
          .success(function(data){
            //当创建失败时
            if(data.status && data.status == 'failure') {
              errorShowServices.alertErrorMessage('创建失败', data.message);
            }
            else {
              alert('创建成功');
              loadAddress();
            }

          })
          .error(function(data){

          });

      },
      //dismiss function
      function(){

      }
    );
  };

  /**
   * 打开编辑模态框
   * 通过show方法传一个地址列表给控制器
   * 暂时不测试
   */

  $scope.editAddress = function(id) {
    $scope.modalInstance = $modal.open({
      templateUrl: 'ngApp/common/tpls/addressModalContent.html',
      controller: 'addressModalController',
      //size: size,

      resolve: {
        addressList: function(){
          return addressServices.show(id)

            .success(function(data){
              return data;
            })
            .error(function(data){
              console.log(data.error);
            })
        }
      }
    });

    $scope.modalInstance.result.then(function(addressData){
        addressServices.update(id,addressData)
          .success(function(data){
            if(data.status && data.status == 'failure') {
              errorShowServices.alertErrorMessage('编辑失败', data.message);
            }else{
              alert('编辑成功');
              loadAddress();

            }
          })
          .error(function(data){

          });
      },
      //dismiss function
      function(){

      }
    );
  }



}]);


/**
 * 模态框控制器
 */
addressController.controller('addressModalController',['$scope','$modalInstance','addressList','districtServices',function($scope,$modalInstance,addressList,districtServices) {
  //如果是创建框,则addressList为null
  if(!addressList){
    $scope.addressInfo = {
      name: '',
      district: {
        province: {
          id: -1,
          name: ''
        },
        city: {
          id: -1,
          name: ''
        },
        region: {
          id: -1,
          name: ''
        }
      },
      location: '',
      phone: '',
      postcode: '',
      default: 0
    };
  }else{
    //如果是编辑框,则直接用addressList
    $scope.addressInfo = addressList.data;
  }

  //地区列表
  $scope.districtList = {
    provinceList: [],
    cityList: [],
    regionList: []
  };

  //地区请求操作,根据所选的id改变地区列表
  $scope.districtListHandle = (function(){
    //一开始就设置省列表


    return {
      setProvinceList: function () {
        districtServices.getProvince()
          .success(function (data) {
            $scope.districtList.provinceList = data;
          })
          .error(function (data) {
            console.log(data);
          });

      },
      setCityList: function (provinceId, provinceName) {
        if (provinceId > 0) {
          districtServices.getCity(provinceId)
            .success(function (data) {
              $scope.districtList.cityList = data;
            })
            .error(function (data) {
              console.log(data);
            });
        }
      },
      setRegionList: function (provinceId, cityId, cityName) {
        if (provinceId > 0 && cityId > 0) {
          districtServices.getRegion(provinceId, cityId)
            .success(function (data) {
              $scope.districtList.regionList = data;
            })
            .error(function (data) {
              console.log(data);
            });
        }
      }
    }
  }());
  $scope.districtListHandle.setProvinceList();
  var provinceId = $scope.addressInfo.district.province.id;
  var cityId = $scope.addressInfo.district.city.id;
  if(provinceId > 0) {
    $scope.districtListHandle.setCityList(provinceId);
  }
  if(provinceId > 0 && cityId > 0) {
    $scope.districtListHandle.setRegionList(provinceId,cityId);
  }


  //保存操作
  $scope.ok = function() {

    $scope.addressInfo.regionId = $scope.addressInfo.district.region.id;
    $modalInstance.close($scope.addressInfo);
  };

  //退出
  $scope.dismiss = function(){
    $modalInstance.dismiss('cancel');
  };



}]);